package com.yi.wood.web.service.impl;

import com.yi.wood.entity.Goods;
import com.yi.wood.service.impl.AbstractGoodsServiceImpl;
import com.yi.wood.web.ctrl.dto.GoodsDto;
import com.yi.wood.web.service.GoodsProService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author MoYi
 * Created time 2019/4/11 15:37
 */
@Service("goodsProService")
public class GoodsProServiceImpl extends AbstractGoodsServiceImpl implements GoodsProService {
    @Override
    public Page<GoodsDto> pageGoodsList(String name, String goodsNo, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of((pageNum - 1), pageSize);
        Page<Goods> page = goodsDao.findAll(new Specification<Goods>() {
            List<Predicate> listPre = new ArrayList<>();

            @Override
            public Predicate toPredicate(Root<Goods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                if (!StringUtils.isEmpty(name)) {
                    listPre.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + name + "%"));
                }
                if (!StringUtils.isEmpty(goodsNo)) {
                    listPre.add(criteriaBuilder.like(root.get("goodsNo").as(String.class), "%" + goodsNo + "%"));
                }
                Predicate[] pre = new Predicate[listPre.size()];
                criteriaQuery.where(listPre.toArray(pre));
                return criteriaBuilder.and(pre);
            }
        }, pageable);

        return new PageImpl<>(toDtos(page.getContent()), pageable, page.getTotalElements());
    }

    private List<GoodsDto> toDtos(List<Goods> list) {
        List<GoodsDto> goodsDtos = new ArrayList<>(list.size());
        list.forEach(goods -> {
            GoodsDto dto = new GoodsDto();
            BeanUtils.copyProperties(goods, dto);
            goodsDtos.add(dto);
        });
        return goodsDtos;
    }
}
